from django.core.urlresolvers import get_callable
from django.core.exceptions   import ValidationError

def validate_callable_objects(values):
    index = 0
    try:
        for value in values:
            try:
                validate_callable_object(value)
                index = index + 1
            except ValidationError,e:
                raise ValidationError,"Item {0}: {1}".format(index+1,e)
    except TypeError:
        raise ValidationError,"Values must be iteratable"
    if not index:
        raise ValidationError,"Values can not be empty"

def validate_callable_names(values):
    if not isinstance(values,basestring):
        raise ValidationError,"Values must be a string"
    index = 0
    for value in values.split(','):
        try:
            validate_callable_name(value)
            index = index + 1
        except ValidationError,e:
            raise ValidationError,"Item {0}: {1}".format(index+1,e)
    if not index:
        raise ValidationError,"Value can not be empty"

def validate_callable_object(value):
    if not callable(value):
        raise ValidationError,"Value is not callable"
    if not hasattr(value,'__module__') or not hasattr(value,'__name__'):
        raise ValidationError,"Value must be accessibale via a module"

def validate_callable_name(name):
    if not isinstance(name,basestring):
        raise ValidationError,"Value must be a string"
    try:
        value = get_callable(name.strip())
    except Exception,e:
        raise ValidationError,e
    validate_callable_object(value)

